<template>
  <div class="doc-import-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">文档导入</h2>
    </div>

    <!-- 导入配置 -->
    <el-card class="config-card">
      <template #header>
        <span>导入配置</span>
      </template>
      
      <el-form
        ref="formRef"
        :model="importConfig"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="文档源" prop="source">
          <el-select v-model="importConfig.source" @change="handleSourceChange">
            <el-option label="Cursor 官方文档" value="cursor" />
            <el-option label="自定义源" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="importConfig.source === 'custom'" label="基础URL" prop="baseUrl">
          <el-input v-model="importConfig.baseUrl" placeholder="https://example.com" />
        </el-form-item>
        
        <el-form-item label="请求延迟">
          <el-input-number
            v-model="importConfig.delay"
            :min="500"
            :max="10000"
            :step="500"
          />
          <span class="ml-2 text-gray-500">毫秒</span>
        </el-form-item>
        
        <el-form-item label="批量大小">
          <el-input-number
            v-model="importConfig.batchSize"
            :min="1"
            :max="50"
          />
          <span class="ml-2 text-gray-500">每批处理文档数</span>
        </el-form-item>
        
        <el-form-item label="下载图片">
          <el-switch v-model="importConfig.imageDownload" />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="importing"
            @click="startImport"
          >
            开始导入
          </el-button>
          <el-button v-if="importing" @click="stopImport">
            停止导入
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 导入进度 -->
    <el-card v-if="importTask" class="progress-card">
      <template #header>
        <span>导入进度</span>
      </template>
      
      <div class="progress-info">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">状态</div>
              <div class="stat-value">
                <el-tag :type="getStatusType(importTask.status)">
                  {{ getStatusText(importTask.status) }}
                </el-tag>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">进度</div>
              <div class="stat-value">
                {{ importTask.processedPages }} / {{ importTask.totalPages }}
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">完成率</div>
              <div class="stat-value">
                {{ getProgress() }}%
              </div>
            </div>
          </el-col>
        </el-row>
        
        <el-progress
          :percentage="getProgress()"
          :status="getProgressStatus()"
          class="mt-4"
        />
      </div>
    </el-card>

    <!-- 导入日志 -->
    <el-card v-if="importTask?.logs?.length" class="logs-card">
      <template #header>
        <div class="logs-header">
          <span>导入日志</span>
          <div>
            <el-button size="small" @click="clearLogs">清空日志</el-button>
            <el-button size="small" type="primary" @click="exportLogs">
              导出日志
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="logs-container">
        <div
          v-for="(log, index) in importTask.logs"
          :key="index"
          :class="['log-item', `log-${log.level}`]"
        >
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <el-tag :type="getLogType(log.level)" size="small">
            {{ log.level.toUpperCase() }}
          </el-tag>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </el-card>

    <!-- 快速导入 -->
    <el-card class="quick-import-card">
      <template #header>
        <span>快速导入</span>
      </template>
      
      <p class="mb-4">点击下方按钮快速导入预设的文档数据：</p>
      
      <el-space>
        <el-button @click="quickImport('cursor-basic')">
          导入 Cursor 基础文档
        </el-button>
        <el-button @click="quickImport('cursor-advanced')">
          导入 Cursor 高级文档
        </el-button>
        <el-button @click="quickImport('all')">
          导入全部文档
        </el-button>
      </el-space>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useDocsStore } from '@/stores/docs'
import type { DocImportConfig, DocImportTask, DocImportLog } from '@/types/docs'
import { importCursorDocs } from '@/utils/doc-importer'

const docsStore = useDocsStore()

// 状态
const importing = ref(false)
const formRef = ref<FormInstance>()

// 导入配置
const importConfig = reactive<DocImportConfig>({
  source: 'cursor',
  baseUrl: 'https://cursor-docs.apifox.cn/',
  delay: 2000,
  batchSize: 10,
  imageDownload: true,
  imagePrefix: 'cursor-docs',
  selectors: {
    title: 'h1',
    content: '.content',
    navigation: '.nav',
    code: 'pre code'
  }
})

// 表单验证规则
const formRules = {
  source: [
    { required: true, message: '请选择文档源', trigger: 'change' }
  ],
  baseUrl: [
    { required: true, message: '请输入基础URL', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
  ]
}

// 导入任务
const importTask = computed(() => docsStore.importTask)

// 处理文档源变化
const handleSourceChange = (value: string) => {
  if (value === 'cursor') {
    importConfig.baseUrl = 'https://cursor-docs.apifox.cn/'
  } else {
    importConfig.baseUrl = ''
  }
}

// 开始导入
const startImport = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      await ElMessageBox.confirm(
        '导入操作可能需要较长时间，确定要开始吗？',
        '确认导入',
        {
          confirmButtonText: '开始导入',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      importing.value = true
      
      if (importConfig.source === 'cursor') {
        // 使用内置的 Cursor 文档导入器
        await importCursorDocs({
          delay: importConfig.delay,
          batchSize: importConfig.batchSize,
          imageDownload: importConfig.imageDownload,
          imagePrefix: importConfig.imagePrefix
        })
      } else {
        // 使用通用导入器
        await docsStore.importDocs(importConfig)
      }
      
      ElMessage.success('文档导入完成！')
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.message || '导入失败')
      }
    } finally {
      importing.value = false
    }
  })
}

// 停止导入
const stopImport = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要停止导入吗？',
      '停止导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 实现停止导入逻辑
    importing.value = false
    ElMessage.info('导入已停止')
  } catch {
    // 用户取消
  }
}

// 快速导入
const quickImport = async (type: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要导入${type === 'all' ? '全部' : type}文档吗？`,
      '快速导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    importing.value = true
    
    // 根据类型设置不同的导入参数
    const config: Partial<DocImportConfig> = {
      delay: 1000,
      batchSize: type === 'all' ? 20 : 10
    }
    
    await importCursorDocs(config)
    ElMessage.success('快速导入完成！')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('快速导入失败')
    }
  } finally {
    importing.value = false
  }
}

// 清空日志
const clearLogs = () => {
  if (importTask.value) {
    importTask.value.logs = []
  }
}

// 导出日志
const exportLogs = () => {
  if (!importTask.value?.logs?.length) {
    ElMessage.warning('没有日志可导出')
    return
  }
  
  const logs = importTask.value.logs.map(log => 
    `[${formatTime(log.timestamp)}] [${log.level.toUpperCase()}] ${log.message}`
  ).join('\n')
  
  const blob = new Blob([logs], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `import-logs-${new Date().toISOString().slice(0, 10)}.txt`
  link.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('日志已导出')
}

// 计算进度
const getProgress = () => {
  if (!importTask.value || !importTask.value.totalPages) return 0
  return Math.round((importTask.value.processedPages || 0) / importTask.value.totalPages * 100)
}

// 获取进度状态
const getProgressStatus = () => {
  if (!importTask.value) return ''
  if (importTask.value.status === 'failed') return 'exception'
  if (importTask.value.status === 'completed') return 'success'
  return ''
}

// 获取状态类型
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'info',
    running: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '等待中',
    running: '导入中',
    completed: '已完成',
    failed: '失败'
  }
  return map[status] || status
}

// 获取日志类型
const getLogType = (level: string) => {
  const map: Record<string, string> = {
    info: 'info',
    warning: 'warning',
    error: 'danger'
  }
  return map[level] || 'info'
}

// 格式化时间
const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN')
}
</script>

<style scoped>
.doc-import-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.config-card,
.progress-card,
.logs-card,
.quick-import-card {
  margin-bottom: 20px;
}

.progress-info {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.log-item {
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.5;
  font-family: monospace;
}

.log-time {
  color: #909399;
  margin-right: 8px;
}

.log-message {
  margin-left: 8px;
}

.log-info {
  color: #606266;
}

.log-warning {
  color: #e6a23c;
}

.log-error {
  color: #f56c6c;
}
</style> 